<?php

namespace App\Service\WorkOrder\Appraise;

use AlibabaCloud\Client\Config\Config;
use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Exports\Appraise\AppraiseExport;
use App\Http\Middleware\OpenShop\FeishuWebAuth;
use App\Jobs\Appraise\Appraise;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Models\Appraise\AppraiseMessageTaskModel;
use App\Models\Appraise\AppraiseModel;
use App\Models\College\CollegeTrainingOrderModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\OperateLogModel;
use App\Models\Common\ResourcesModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Remote\Feishu\FeishuImageRemote;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Scope\Shop\ShopScope;
use App\Service\BaseService;
use App\Service\College\CollegeTrainOrderService;
use App\Service\Common\CommonService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\OrderService as OpenShopOrder;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\WorkOrder\Web\ApplyService;
use Exception;
use Guanguans\Notify\Factory;
use Guanguans\Notify\Messages\FeiShu\CardMessage;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Kuafu\CsvStream\Exporter;
use Kuafu\GeneralFs\BuildFs;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class AppraiseService extends BaseService
{

    const DEFAULT_APPRAISE_EXPIRE_DAY = 3;//3个月内已完成的工单，可以评价

    /**
     * 发布评价
     * @param $request
     * @param int $shopId
     * @param int $currentUid
     * @param string $desc
     * @param array $img
     * @param array $tags
     * @param string $mobile
     * @throws GuzzleException
     */
    public static function add($request, int $shopId, int $currentUid, string $desc = '', array $img = [], array $tags = [], $mobile = '')
    {
        self::orderStatusValidate($request->type, $request->workOrderNo ?? "");//验证订单状态
        try {
            DB::beginTransaction();
            $appraiseRoleList = [];
            $dealUid          = $appraiseRoleList ? array_keys($appraiseRoleList)[0] : 0;
            $tag = $tagDesc = '';
            if ($tags) {
                $tag          = "," . implode(',', $tags) . ",";//搜索时 匹配 ,1,
                $getNewConfig = self::getNewConfig($request->type);
                if ($getNewConfig && isset($getNewConfig['stars'][$request->score]['tag'])) {
                    foreach ($tags as $v) {
                        if (isset($getNewConfig['stars'][$request->score]['tag'][$v])) {
                            $tagDesc .= $getNewConfig['stars'][$request->score]['tag'][$v] . ',';
                        }
                    }
                    $tagDesc = rtrim($tagDesc, ',');//删除最后一个,
                }
            }
            $addData = [
                'workOrderNo' => $request->workOrderNo ?? "",         //工单号
                'shopId'      => $shopId,                             //店铺id
                'type'        => $request->type,                      //类型1-工单 2-App
                'score'       => $request->score,                     //分数1-5
                'desc'        => $desc,                               //描述
                'tag'         => $tag,                                //评价标签,多个id以逗号分割
                'dealUid'     => $dealUid,                            //处理人id
                'mobile'      => $mobile,                             //手机号
                'tagDesc'     => $tagDesc,                            //评价标签文案入库
            ];
            if ($request->score == AppraiseModel::SCORE_FIVE) {//五星好评-状态完成
                $addData['status']   = AppraiseModel::STATUS_DEAL_SUC;
                $addData['dealTime'] = time();
            }
            $appraise         = AppraiseModel::addAppraise($addData);
            $createTime = date('Y-m-d H:i:s');
            //保存资源
            if ($img && is_array($img)) {
                foreach ($img as $file) {
                    ResourcesModel::moduleBusinessResourcesBuild(
                        ResourcesModel::MODULE_TYPE_APPRAISE,
                        ResourcesModel::BUSINESS_APPRAISE,
                        'appraiseImg',
                        (int)$appraise->id,
                        ltrim(parse_url($file, PHP_URL_PATH), '/')
                    );
                }
                ResourcesModel::moduleBusinessResourcesSave();
            }
            // 操作日志
            OperateLogModel::add(
                OperateLogModel::BUSINESS_APPRAISE,
                $appraise->id,
                $appraise->id,
                '新建评价',
                '新建评价',
                OperateLogModel::STATUS_WAIT,
                $currentUid,
            );
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            Log::info("新增评价失败：" . $exception->getMessage());
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "新增评价失败");
        }

        dispatch(
            (new Appraise(
                [
                    'shopId'      => $shopId,
                    'currentUid'  => $currentUid,
                    'appraiseId'  => (int)$appraise->id,
                    'workOrderNo' => (string)$request->workOrderNo,
                    'type'        => (int)$request->type,
                    'score'       => (int)$request->score,
                    'tagDesc'     => $tagDesc,
                    'desc'        => (string)$desc,
                    'createTime'  => $createTime,
                    'img'         => $img,
                    'replyData'   => [],
                ]
            ))
        )->onQueue(Appraise::QUEUE_NAME);
        //飞书通知-评价反馈客服飞书群群+圈对应的人（客服某一个人）
//        self::sendFSMessage($shopId, $currentUid, (int)$appraise->id, (string)$request->workOrderNo, (int)$request->type, (int)$request->score, $tagDesc, (string)$desc, [], $createTime);
    }


    /**
     * 飞书机器人通知
     * @param int $shopId
     * @param int $currentUid
     * @param int $appraiseId
     * @param string $workOrderNo
     * @param int $type
     * @param int $score
     * @param string $tagText
     * @param string $desc
     * @param array $shareImgList
     * @param $createTime
     * @param array $replyData
     * @throws GuzzleException
     * @throws Exception
     */
    public static function sendFSMessage(
        int $shopId,
        int $currentUid,
        int $appraiseId,
        string $workOrderNo,
        int $type,
        int $score,
        string $tagText,
        string $desc,
        array $shareImgList = [],
        $createTime,
        array $replyData = []
    )
    {
        $shopInfo  = (object)current((new RmsShopApi())->getShopByIds([$shopId])["data"]["shopList"]);//门店信息
        $userIds = [$currentUid];
        if ($replyData) {
            $userIds = [$currentUid, $replyData['replyUserId']];
        }
        $userInfos = collect(RmsUserRemote::getRmsUserByIds($userIds))->keyBy('id');

        $buttonText = '立即处理';
        $dealText = "待处理";//vsprintf("待处理 <at id=%s></at>", array_values($appraiseRoleList)[0]);
        if ($score == AppraiseModel::SCORE_FIVE) {//任务状态：5星以下：待处理+@业务处理人  5星：已完成  （不需要圈人）
            $dealText = "已完成";
            $buttonText = '查看详情';
        }
        $scoreText = "";
        if ($score) {
            $scoreText = $score . "星·";
        }
        if ($desc) {
            $desc = str_replace(array("\r", "\n"), '\n', $desc);
        }
        $shopCode = $shopInfo->shopCode ?? "";
        $shopName = $shopCode . $shopInfo->name ?? "";
        $typeText = AppraiseModel::TYPE_CN_MAP_TEXT[$type] ?? "";
        $jumpUrl  = \App\Service\OpenShop\Feishu\BaseService::getAppraiseInfoWenAppUrl($appraiseId);

        $problemPidText = $problemChildIdText = '';
        $problemPid     = $problemChildId = 0;
        if ($workOrderNo && $type == AppraiseModel::TYPE_WORK_ORDER) {//工单类型
            $applyMain = WorkOrderApplyMainModel::query()->where("workOrderNo", $workOrderNo)->first();
            if ($applyMain) {
                $problemPidText     = OrderEnum::PROBLEM_PID_TEXT[$applyMain->problemPid] ?? '';
                $problemChildIdText = OrderEnum::TYPE_RELATION_MAP[$applyMain->problemPid][$applyMain->problemChildId] ?? '';
                $problemPid         = $applyMain->problemPid ?? 0;
                $problemChildId     = $applyMain->problemChildId ?? 0;
            }
        }
        // 未查询到店铺的省市区信息时，取开店地址表的信息
        if (((!$shopInfo->addressPrefix || $shopInfo->addressPrefix == '--') || !$shopInfo->province || !$shopInfo->branch) && $shopCode) {
            $getOpenShopSignOrderData = self::getOpenShopSignOrderData($shopCode);
            if ((!$shopInfo->addressPrefix || $shopInfo->addressPrefix == '--') && $getOpenShopSignOrderData['addressPrefix']) {
                $shopInfo->addressPrefix = $getOpenShopSignOrderData['addressPrefix'];
            }
            if (!$shopInfo->province && $getOpenShopSignOrderData['province']) {
                $shopInfo->province = $getOpenShopSignOrderData['province'];
            }
            if (!$shopInfo->branch && $getOpenShopSignOrderData['branch']) {
                $shopInfo->branch = $getOpenShopSignOrderData['branch'];
            }
        }
        try {
            $manager = OrganizationManageService::getOrganizationInfoByType(
                OrganizationManageEnum::TYPE_BRANCH_OFFICE,
                $shopInfo->province
            );
        } catch (Exception $exception) {//处理 该省区没有绑定开店组织 不显示
            $manager = [];
        }

        $shopProvince    = '（' . $shopInfo->branch . '）' . $shopInfo->addressPrefix;
        $provincialTotal = $manager["operationName"] ?? "";//省总
        $mergeData       = [];
        if ($replyData) {
            $templateJsonName = '/AppraiseFsTemplateReply.blade.php';
            $color            = 'blue';
            $buttonText       = '查看详情';
            $dealText         = AppraiseModel::STATUS_MAP_TEXT[$replyData['status']] ?? "已完成";

            $logList = [];
            OperateLogModel::getData(OperateLogModel::BUSINESS_APPRAISE, $appraiseId, $appraiseId)
                ->map(
                    function ($log) use (&$logList) {
                        if ($log->logName == '新增回复') {
                            $logList[] = [
                                'userName'   => $log->userName ? $log->userName : "系统",
                                'logContent' => str_replace(["\n", "\r", "\r\n", PHP_EOL], "", $log->logContent),
                                'createdAt'  => $log->createdAt->toDateTimeString(),
                            ];
                        }
                    }
                );

            $mergeData = [
                'logList'   => $logList,
            ];
            $title     = "【处理进度提醒】" . $scoreText . (AppraiseModel::TYPE_FS_SEND_MAP_TEXT[$type] ?? '反馈评价通知') .
                "有新的处理进度，请注意（" . $shopCode . "）";
        } else {
            $templateJsonName = '/AppraiseFsTemplate.blade.php';
            $color            = AppraiseModel::SCORE_MAP_COLOR[$score] ?? 'blue';
//            $title            = "【" . $scoreText . (AppraiseModel::TYPE_FS_SEND_MAP_TEXT[$type] ?? '反馈评价通知')
//                . "】有新的" . $typeText . "已提交，请注意（" . $shopCode . "）";

            $title = vsprintf(
                "【%s%s】有新的%s已提交，请注意（%s）", [
                    in_array($type, [AppraiseModel::TYPE_APP_CHOOSE_SUGGESTION, AppraiseModel::TYPE_APP_PROCESS_IMPROVE])  ? "" : $scoreText,
                    (AppraiseModel::TYPE_FS_SEND_MAP_TEXT[$type] ?? '反馈评价通知'),
                    $typeText,
                    $shopCode
                ]
            );
        }

        // 全部的消息卡片，涉及到加盟商信息的地方，我们都调整下显示逻辑，加星号处理 刘仁杰2892 13361868635 调整为： 刘**  133****8635
        $username = CommonService::getUserInfoHide($userInfos[$currentUid]['username'] ?? '', 'name');
        $mobile   = CommonService::getUserInfoHide($userInfos[$currentUid]['mobile'] ?? '', 'mobile');

        $templateData = [
            "shopName"        => $shopName,
            "submitName"      => $username . " " . $mobile,
            "scoreText"       => in_array($type, [AppraiseModel::TYPE_APP_CHOOSE_SUGGESTION, AppraiseModel::TYPE_APP_PROCESS_IMPROVE]) ? "" :
                $score . '星（' . (AppraiseModel::SCORE_MAP_TEXT[$score] ?? "") . '）',
            "typeText"        => $typeText,
            "statusText"      => $dealText,
            "order"           => $workOrderNo ?? "无",
            "tagText"         => $tagText ?? "无",
            "createdTime"     => $createTime,
            "desc"            => $desc ?? "无",
            "shareImgList"    => $shareImgList ? array_chunk($shareImgList, 3) : [],
            "buttonText"      => $buttonText,
            "jumpUrl"         => $jumpUrl,
            "color"           => $color,
            "title"           => $title,
            "shopProvince"    => $shopProvince,
            "provincialTotal" => $provincialTotal,
            "problemPidText"  => $problemPidText,
            "problemChildIdText" => $problemChildIdText,
        ];
        if ($mergeData) {
            $templateData = array_merge($templateData, $mergeData);
        }
        $templateJson = view()->file(
            app_path("Remote/Feishu/FsTemplate/Appraise") . $templateJsonName, $templateData
        )->render();

        $robot = SendFs::ROBOT_APPRAISE;
        if ($score == AppraiseModel::SCORE_FIVE) {//5星单独群
            $robot = SendFs::ROBOT_APPRAISE_FIVE_STAR;
        }
        $appraiseSendFsConfig = Cache::remember(
            'tiger:workOrder:appraise:sendFsConfig', getSwitchCacheTime(86400), function () {
            return json_decode(
                ConfigModel::query()
                    ->where('module', 'appraise')
                    ->where('name', 'appraiseSendFsConfig')
                    ->value('value') ?? [], true
            );
        });
        if ($appraiseSendFsConfig && in_array($shopId, $appraiseSendFsConfig)) {
            $robot = SendFs::ROBOT_APPRAISE_TEST;
        }


        $match = function ($string, $keyword) {
            $pattern = '/(' . implode('|', $keyword) . ')/';
            return (bool) preg_match($pattern, $string);
        };


        //设定规则同步
        if ($match($tagText ?? '', [
                '设备问题',
                '订货问题',
                '选品建议',
            ]) ||
            $match($problemPidText, [
                '选品建议',
                '仓储配送问题',
            ]) ||
            $match($typeText, [
                '选品建议',
                '仓储配送',
            ]) ||
            $match($problemChildIdText, [
                OrderEnum::PROBLEM_PID_4_CHILDREN_MAPPING[OrderEnum::PROBLEM_PID_4_CHILDREN_1],
                OrderEnum::PROBLEM_PID_4_CHILDREN_MAPPING[OrderEnum::PROBLEM_PID_4_CHILDREN_13],
                OrderEnum::PROBLEM_PID_4_CHILDREN_MAPPING[OrderEnum::PROBLEM_PID_4_CHILDREN_2]
            ]) ||
            $match($desc ?? '', [
                '物流',
                '配送',
                '送货',
                '司机'
            ])
        ) {
            //同步消息到供应链群
            BuildFs::newRobot(SendFs::ROBOT_WORK_ORDER_AUDIT_SUPPLIER, BuildFs::MSG_TYPE_CARD)
                ->setCardContent(json_decode($templateJson, true))
                ->send();
        }


//        SendFs::newRobot($robot)->setCardMessageBody(json_decode($templateJson, true))->send();
        BuildFs::newRobot($robot, BuildFs::MSG_TYPE_CARD)
            ->setCardContent(json_decode($templateJson, true))
            ->send();

        //按照反馈的门店所在省市区，评价内容和回复内容，对应的省区四驱群
        if (config('app.env') == 'prod') {
            $areaRobotJsonConfig = Cache::remember(
                'tiger:workOrder:appraise:areaRobots', getSwitchCacheTime(86400), function () {
                return json_decode(
                    ConfigModel::query()
                        ->where('module', 'appraise')
                        ->where('name', 'areaRobots')
                        ->value('value') ?? [], true
                );
            }
            );
            $robotConfig = [];
            foreach ($areaRobotJsonConfig as $area => $robot) {
                $provinceLen = mb_strlen($area);
                if (mb_substr($shopInfo->addressPrefix, 0, $provinceLen) == $area) {
                    $robotConfig['token']  = substr($robot['webhook'], (strripos($robot['webhook'], '/') + 1));
                    $robotConfig['secret'] = $robot['sign'];
                }
            }
            if ($robotConfig) {
                Factory::feiShu()
                    ->setToken($robotConfig['token'])
                    ->setSecret($robotConfig['secret'])
                    ->setMessage(new CardMessage(json_decode($templateJson, true)))
                    ->send();
            }

            // 评价反馈不同类型对应群通知
            $typeRobotsJsonConfig = Cache::remember(
                'tiger:workOrder:appraise:typeRobots', getSwitchCacheTime(86400), function () {
                return json_decode(
                    ConfigModel::query()
                        ->where('module', 'appraise')
                        ->where('name', 'typeRobots')
                        ->value('value') ?? "", true
                );
            }
            );

            $typeRobotsConfig = [];
            foreach ($typeRobotsJsonConfig as $k => $robot) {
                if (isset(AppraiseModel::TYPE_MAP_TEXT[$type]) && $k == AppraiseModel::TYPE_MAP_TEXT[$type]) {

                    // 品质异常问题 直接推送到品控群
                    if ($type == AppraiseModel::TYPE_WORK_ORDER && isset($robot['problemPid']) && $problemPid != $robot['problemPid']) {
                        continue;
                    }

                    // 问题反馈-门店设计问题 直接推送到【品牌设计中心】部门飞书群
                    if ($type == AppraiseModel::TYPE_APP_COMPLAINT && !$match($tagText ?? '', ['门店设计问题'])) {
                        continue;
                    }

                    $typeRobotsConfig['token']  = substr($robot['webhook'], (strripos($robot['webhook'], '/') + 1));
                    $typeRobotsConfig['secret'] = $robot['sign'];
                }
            }
            if ($typeRobotsConfig) {
                Factory::feiShu()
                    ->setToken($typeRobotsConfig['token'])
                    ->setSecret($typeRobotsConfig['secret'])
                    ->setMessage(new CardMessage(json_decode($templateJson, true)))
                    ->send();
            }
        }
    }

    /**
     * 获取评价对应内容配置
     * @param int $type
     * @return array
     */
    public static function getConfig($type = AppraiseModel::TYPE_WORK_ORDER): array
    {
        $data = json_decode(
            ConfigModel::query()
                ->where('module', 'appraise')
                ->where('name', 'appraiseConfig')
                ->value('value') ?? '', true
        );
        if (!$data) {
            return [];
        }
        if ($type == AppraiseModel::TYPE_ALL) {
            return $data;
        }
        return $data[AppraiseModel::TYPE_MAP_TEXT[$type]] ?? [];
    }

    /**
     * 评价列表
     * @param string $startTime
     * @param string $endTime
     * @param string $dealStartTime
     * @param string $dealEndTime
     * @param int $status
     * @param int $score
     * @param int $type
     * @param string $tag
     * @param string $shopInfo
     * @param int $dealUid
     * @param int $export
     * @param int $pageSize
     * @param int $pageNum
     * @param int $currentUid
     * @return array
     * @throws GuzzleException
     */
    public static function lists(
        string $startTime,
        string $endTime,
        string $dealStartTime,
        string $dealEndTime,
        int $status,
        int $score,
        int $type,
        string $tag,
        string $shopInfo,
        int $dealUid,
        int $export,
        int $pageSize,
        int $pageNum,
        int $currentUid
    ): array
    {
        $paginator = AppraiseModel::query()
            ->when(
                $startTime, function ($query) use ($startTime) {
                $query->where('createdAt', '>=', strtotime($startTime));
            })
            ->when(
                $endTime, function ($query) use ($endTime) {
                $query->where('createdAt', '<', strtotime($endTime) + 86400);
            })
            ->when(
                $dealStartTime, function ($query) use ($dealStartTime) {
                $query->where('dealTime', '>=', strtotime($dealStartTime));
            })
            ->when(
                $dealEndTime, function ($query) use ($dealEndTime) {
                $query->where('dealTime', '<', strtotime($dealEndTime) + 86400);
            })
            ->when(
                $type > 0, function ($query) use ($type) {
                $query->where('type', $type);
            })
            ->when(
                $status > 0, function ($query) use ($status) {
                $query->where('status', $status);
            })
            ->when(
                $score > 0, function ($query) use ($score) {
                $query->where('score', $score);
            })
            ->when(
                $dealUid > 0, function ($query) use ($dealUid) {
                $query->where('dealUid', $dealUid);
            })
            ->when(
                ShopScope::getShopIdsArr(), function ($query) {
                $query->whereIn("shopId", ShopScope::getShopIdsArr());
            })
            ->when($shopInfo, function ($query) use ($shopInfo) {
                $shopInfos = RmsShopRemote::getShopInfoByLikeSearch($shopInfo);
                $shopIds   = array_column($shopInfos["shopInfo"], "id");
                if ($shopIds) {
                    $query->whereIn('shopId', $shopIds);
                } else {
                    $query->where('shopId', 0);
                }
            })
            ->when($tag, function ($query) use ($tag) {
                $tag = explode(',', $tag);
                if ($tag && is_array($tag)) {
                    $str = "";
                    foreach ($tag as $v) {
                        $str .= " (tag like '%,{$v},%') " . 'or';
                        //                        $query->where('tag', 'like', "%,{$v},%");
                    }
                    $str = substr($str, 0, -2);
                    $query->whereRaw(" 1=1 and ( {$str} )");// and  1=1 and (  (tag like '%,1,%') or (tag like '%,2,%')  )
                }
            })
            ->orderByDesc('id')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
        $shopIds   = collect($paginator->items())->pluck('shopId')->toArray();
        //门店信息
        $shopInfo  = (new RmsShopApi())->getShopByIds($shopIds, ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
        $shopList  = array_column($shopInfo, null, 'id');
        $dealUids  = collect($paginator->items())->pluck('dealUid')->toArray();
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($dealUids)['data'])->keyBy('id');
        /*$appraiseRoleList = self::getDealConfig();//获取配置的人
        if ($appraiseRoleList) {
            $appraiseRoleList = array_keys($appraiseRoleList);
        }*/

        $lists     = $paginator->map(
            function (AppraiseModel $appraiseModel) use ($currentUid, $userInfos, $shopList) {
                $tagText = $appraiseModel->tagDesc ?? "";
                $appraiseModel->tag = ltrim($appraiseModel->tag, ',');
                $appraiseModel->tag = rtrim($appraiseModel->tag, ',');
                if ($tagText == '' && $appraiseModel->tag && $appraiseModel->score) {
                    foreach (explode(',', $appraiseModel->tag) as $v) {
                        $getConfigAll = self::getNewConfig($appraiseModel->type);
                        if ($getConfigAll) {
                            $tagText .= ($getConfigAll['stars'][$appraiseModel->score]['tag'][$v] ?? "") . ",";
                        }
                    }
                    $tagText = rtrim($tagText, ',');//去除最后一个换行符
                }
                /*$isDeal = $currentUid && $appraiseRoleList ? in_array($currentUid, $appraiseRoleList) : false;
                if ($isDeal && $appraiseModel->dealUid > 0 && $appraiseModel->dealUid != $currentUid) {//已有处理人，则不会再分派处理人
                    $isDeal = false;
                }*/
                return [
                    'id'          => $appraiseModel->id,
                    'workOrderNo' => $appraiseModel->workOrderNo,
                    'shopId'      => $appraiseModel->shopId,
                    'shopCode'    => $shopList[$appraiseModel->shopId]['shopCode'] ?? '-',
                    'shopName'    => $shopList[$appraiseModel->shopId]['name'] ?? '-',
                    'createdAt'   => $appraiseModel->createdAt->toDateTimeString(),
                    'manageName'  => $userInfos[$appraiseModel->dealUid]['username'] ?? '系统',
                    'status'      => $appraiseModel->status,
                    'type'        => $appraiseModel->type,
                    'score'       => $appraiseModel->score,
                    'desc'        => $appraiseModel->desc,
                    'tag'         => explode(',', $appraiseModel->tag),
                    'dealTime'    => formatDate($appraiseModel->dealTime),
                    'tagText'     => $tagText,
                    'typeText'    => AppraiseModel::TYPE_CN_MAP_TEXT[$appraiseModel->type] ?? "",
                    'isDeal'      => true,//是否处理人
                ];
            }
        );
        if ($export) {
            return excelDownload(new AppraiseExport(Collect($lists)), '评价反馈-' . date('Y-m-d') . "-" . time());
//            self::appraiseExport($startTime,$endTime,$lists);
        }
        return [
            'pageNum'   => $paginator->currentPage(),
            'pageSize'  => $paginator->perPage(),
            'pageCount' => ceil($paginator->total() / $paginator->perPage()),
            'count'     => $paginator->total(),
            'lists'     => $lists,
        ];
    }

    /**
     * 评价导出csv
     * @param $startTime
     * @param $endTime
     * @param $lists
     * @return array
     */
    public static function appraiseExport($startTime, $endTime, $lists): array
    {
        $exporter = new Exporter('评价反馈-' . date('Y-m-d') . "-" . time() . '.csv');
        $exporter->writeHeaders([
            '提交时间',
            '门店',
            '反馈类型',
            '问题标签',
            '评价星级',
            '反馈内容',
            '状态',
            '完成时间',
            '处理人',
        ]);
        foreach ($lists as $item) {
            $exporter->writeLine(
                [
                    $item['createdAt'],
                    $item['shopCode'] . $item['shopName'],
                    AppraiseModel::TYPE_CN_MAP_TEXT[$item['type']] ?? "",
                    $item['tagText'],
                    $item['score'] . "星",
                    $item['desc'],
                    AppraiseModel::STATUS_MAP_TEXT[$item['status']] ?? "",
                    $item['dealTime'],
                    $item['manageName'],
                ]
            );
        }
        $exporter = null;
        /*ini_set('max_execution_time', 100000);
        header("Content-Disposition: attachment; filename=" . urlencode('评价反馈') . "-" . date('Y-m-d') . "-" . time() . '.csv');

        // UTF8的BOM头
        $filename = 'php://output';

        $fd = fopen($filename, 'w+');
        fwrite($fd, "\xEF\xBB\xBF");

        // 表头
        $title = [
            '提交时间',
            '门店',
            '反馈类型',
            '问题标签',
            '评价星级',
            '反馈内容',
            '状态',
            '完成时间',
            '处理人',
        ];

        fputcsv($fd, $title);

        collect($lists)->each(function ($item) use (&$fd) {
            $content = [
                $item['createdAt'],
                $item['shopCode'] . $item['shopName'],
                AppraiseModel::TYPE_CN_MAP_TEXT[$item['type']] ?? "",
                $item['tagText'],
                $item['score'] . "星",
                $item['desc'],
                AppraiseModel::STATUS_MAP_TEXT[$item['status']] ?? "",
                $item['dealTime'],
                $item['manageName'],
            ];

            fputcsv($fd, $content);
            ob_flush();
            flush();
        });

        ob_flush();
        flush();

        if (is_resource($fd)) {
            fclose($fd);
        }
        die;*/
    }

    /**
     * 评价详情
     * @param int $id
     * @param int $source 默认1-后台 2-app
     * @param string $workOrderNo
     * @param int $type
     * @param int $currentUid
     * @return array
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     */
    public static function info($id = 0, $source = 1, $workOrderNo = '', $type = 0, $currentUid = 0): array
    {
        if ($workOrderNo && $type) {
            $info = AppraiseModel::query()->with(['signOrderRel', 'resourcesRel'])->where('workOrderNo', $workOrderNo)->where('type', $type)->first();
            if (!$info) {
                return [];
            }
        } else {
            $info = AppraiseModel::query()->with(['signOrderRel', 'resourcesRel'])->find($id);
            if (!$info) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的评价id");
            }
        }
        /*if ($currentUid > 0 && $info['dealUid'] == 0 && $info['score'] < AppraiseModel::SCORE_FIVE) {//五星未处理状态 第一个处理的人 修改为此单处理人
            $appraiseRoleList = self::getDealConfig();                                               //获取配置的人
            if ($appraiseRoleList && in_array($currentUid, array_keys($appraiseRoleList))) {
                $info['dealUid'] = $currentUid;
            }
        }*/
        //门店信息
        $shopInfo     = (object)current((new RmsShopApi())->getShopByIds([$info['shopId']])["data"]["shopList"]);

        // 未查询到店铺的省市区信息时，取开店地址表的信息
        if (((!$shopInfo->addressPrefix || $shopInfo->addressPrefix == '--') || !$shopInfo->address || !$shopInfo->province
                || !$shopInfo->branch || !$shopInfo->councilorId) && $shopInfo->shopCode) {
            $getOpenShopSignOrderData = self::getOpenShopSignOrderData($shopInfo->shopCode);
            if ((!$shopInfo->addressPrefix || $shopInfo->addressPrefix == '--') && $getOpenShopSignOrderData['addressPrefix']) {
                $shopInfo->addressPrefix = $getOpenShopSignOrderData['addressPrefix'];
            }
            if (!$shopInfo->address && $getOpenShopSignOrderData['addressDetail']) {
                $shopInfo->address = $getOpenShopSignOrderData['addressDetail'];
            }
            if (!$shopInfo->province && $getOpenShopSignOrderData['province']) {
                $shopInfo->province = $getOpenShopSignOrderData['province'];
            }
            if (!$shopInfo->branch && $getOpenShopSignOrderData['branch']) {
                $shopInfo->branch = $getOpenShopSignOrderData['branch'];
            }
            if (!$shopInfo->councilorId && $getOpenShopSignOrderData['managerId']) {
                $shopInfo->councilorId = $getOpenShopSignOrderData['managerId'];
            }
        }
        try {
            $manager = OrganizationManageService::getOrganizationInfoByType(
                OrganizationManageEnum::TYPE_BRANCH_OFFICE,
                $shopInfo->province
            );
        } catch (Exception $exception) {//处理 该省区没有绑定开店组织 不显示
            $manager = [];
        }
        $operationUid = $manager["operationUid"] ?? 0;
        $userIds = array_filter(array_merge([$operationUid, $info['createdByUid'], $info['dealUid'], $shopInfo->councilorId]));
        $userInfo = collect($userIds ? RmsUserRemote::getRmsUserByIds($userIds) : [])->pluck(null, "id");

        $logList = $shopInfos = $resourcesList = $applyContent = [];
        if ($source != AppraiseModel::TYPE_APP) {
            $shopInfos = [
                'id'                    => $info['shopId'],
                'shopCode'              => $shopInfo->shopCode,
                'shopMobile'            => $shopInfo->shopMobile,
                'shopName'              => $shopInfo->name,
                "addressPrefix"         => $shopInfo->addressPrefix,
                "shopAddress"           => $shopInfo->address,
                "supervisor"            => $userInfo->get($shopInfo->councilorId, [])["username"] ?? "",
                "supervisorMobile"      => $userInfo->get($shopInfo->councilorId, [])["mobile"] ?? "",
                "provincialTotalMobile" => $userInfo->get($operationUid, [])["mobile"] ?? "",
                "provincialTotal"       => $manager["operationName"] ?? "",//省总
                'branch'                => $shopInfo->branch,
            ];
            $logList = OperateLogModel::getData(OperateLogModel::BUSINESS_APPRAISE, $info->id, $info->id, 'desc')
                ->map(function ($log) {
                        return [
                            'userId'     => $log->userId,
                            'userName'   => $log->userName ? $log->userName : "系统",
                            'logId'      => $log->logId,
                            'logName'    => $log->logName,
                            'logContent' => $log->logContent,
                            'createdAt'  => $log->createdAt->toDateTimeString(),
                        ];
                    });
            if ($info['workOrderNo']) {
                switch ($info['type']){
                    case AppraiseModel::TYPE_WORK_ORDER://工单
                        $applyContent = ApplyService::contentDetail($info['workOrderNo']);//工单信息
                    break;
                    case AppraiseModel::TYPE_WAIMAI_OPENING://上线外卖
                    case AppraiseModel::TYPE_GROUP_PURCHASE_OPENING://上线团购
                        $info['workOrderNo'] = '';//不关联订单
                        break;
                    case AppraiseModel::TYPE_OPENSHOP_SIGN://开店-签约阶段 关联 开店订单
                    case AppraiseModel::TYPE_OPENSHOP_SET_LOCATION://开店-选址阶段 关联 开店订单
                    case AppraiseModel::TYPE_OPENSHOP_PREPARATION://开店-筹备阶段 关联 开店订单
                    case AppraiseModel::TYPE_OPENSHOP_OPENING://开店-开业阶段 关联 开店订单
                        $applyContent = OpenShopOrder::detail($info['workOrderNo'], 0, true);
                        break;
                    case AppraiseModel::TYPE_OPENSHOP_COLLEGE://商学院培训 关联 培训订单
                        $id = CollegeTrainingOrderModel::query()->where('orderNo', $info['workOrderNo'])->value('id');
                        if ($id) {
                            $getTrainOrderDetail = CollegeTrainOrderService::getTrainOrderDetail($id, FeishuWebAuth::$userId);
                            if ($getTrainOrderDetail) {
                                $applyContent = $getTrainOrderDetail['baseInfo'];
                            }
                        }
                        break;
                    case AppraiseModel::TYPE_KFOS_FIRST_ORDER:
                    case AppraiseModel::TYPE_KFOS_ORDER://首批订货和日常订货 关联 订货单
                        $applyContent = OrmNewOrderRemote::detail(0, $info['workOrderNo']);//获取订货详情
                        $code         = $applyContent['code'] ?? -1;
                        if ($code == 0) {
                            $applyContent = $applyContent['data'] ?? [];
                        }
                        break;
                }
            }
        }
        //资源数据
        collect($info->resourcesRel)->each(
            function (ResourcesModel $resourcesModel) use (&$resourcesList) {
                $resourcesList[] = picturePath($resourcesModel->url);

            }
        )->toArray();
        $info['tag'] = ltrim($info['tag'], ',');
        $info['tag'] = rtrim($info['tag'], ',');
        $getConfig = self::getNewConfig($info['type']);
        $tagText = $scoreText = '';//星级相关文本
        $tagText = $info['tagDesc'] ?? "";
        if ($getConfig && $info['score']) {
            $scoreText = $getConfig['stars'][$info['score']]['desc'] ?? "";
            if ($tagText == '' && $info['tag'] && explode(',', $info['tag'])) {
                foreach (explode(',', $info['tag']) as $v) {
                    $tagText .= ($getConfig['stars'][$info['score']]['tag'][$v] ?? "") . ",";
                }
                $tagText = rtrim($tagText, ',');//去除最后一个换行符
            }
        }
        return [
            'id'               => $info['id'],
            'workOrderNo'      => $info['workOrderNo'],
            'type'             => $info['type'],
            'status'           => $info['status'],
            'score'            => $info['score'],
            'scoreText'        => $scoreText,
            'desc'             => $info['desc'],
            'tag'              => $info['tag'] ? explode(',', $info['tag']) : [],
            'tagText'          => $tagText,
            'dealUid'          => $info['dealUid'],
            'createdAt'        => $info['createdAt']->toDateTimeString(),
            'dealTime'         => formatDate($info['dealTime']),
            'manageName'       => $userInfo->get($info['dealUid'], [])["username"] ?? "",
            'createUserMobile' => $info['mobile'] ? $info['mobile'] : ($userInfo->get($info['createdByUid'], [])["mobile"] ?? ""),
            'createUsername'   => $userInfo->get($info['createdByUid'], [])["username"] ?? "",
            'shopInfo'         => $shopInfos,
            'logList'          => $logList,
            'img'              => $resourcesList,
            'applyContent'     => $applyContent,
            'mobile'           => $info['mobile'],
            'typeText'         => AppraiseModel::TYPE_CN_MAP_TEXT[$info['type']] ?? "",
            'scoreMapText'     => AppraiseModel::SCORE_MAP_TEXT,
        ];
    }

    /**
     * 新增评价回复
     * @param string $desc
     * @param int $tel
     * @param int $id
     * @param int $currentUid
     * @param int $isSendNotice
     */
    public static function addReply(string $desc, int $tel, int $id, int $currentUid,int $isSendNotice)
    {
        $info = AppraiseModel::query()->find($id);
        if (!$info) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的评价id");
        }
        /*if ($currentUid > 0 && $info['dealUid'] == 0 && $info['score'] < AppraiseModel::SCORE_FIVE) {//五星未处理状态 第一个处理的人 修改为此单处理人
            $appraiseRoleList = self::getDealConfig();                                               //获取配置的人
            if ($appraiseRoleList && in_array($currentUid, array_keys($appraiseRoleList))) {
                $info['dealUid'] = $currentUid;
            }
        }
        if ($info['dealUid'] != $currentUid) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "非当前处理人");
        }
        if ($info['status'] == AppraiseModel::STATUS_DEAL_SUC) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "当前状态已处理");
        }*/
        $data = [
            'status'       => AppraiseModel::STATUS_DEAL_ING,
            'updatedByUid' => $currentUid,
            'dealUid'      => $currentUid,
        ];
        AppraiseModel::setInfoById($id, $data);
        $logName    = '获取电话';
        $logContent = '';
        if ($desc) {
            $logName    = '新增回复';
            $logContent = $desc;
        }
        // 操作日志
        OperateLogModel::add(
            OperateLogModel::BUSINESS_APPRAISE,
            $id,
            $id,
            $logName,
            $logContent,
            OperateLogModel::STATUS_WAIT,
            $currentUid,
        );

        if ($desc && $isSendNotice == 1) {//每次回复后，发送卡片到B端评价群
            dispatch(
                (new Appraise(
                    [
                        'shopId'      => $info['shopId'],
                        'currentUid'  => $info['createdByUid'],
                        'appraiseId'  => (int)$id,
                        'workOrderNo' => (string)$info['workOrderNo'],
                        'type'        => (int)$info['type'],
                        'score'       => (int)$info['score'],
                        'tagDesc'     => $info['tagDesc'],
                        'desc'        => (string)$info['desc'],
                        'createTime'  => $info['createdAt']->toDateTimeString(),
                        'img'         => [],
                        'replyData'   => [
                            'status'      => AppraiseModel::STATUS_DEAL_ING,
                            'replyUserId' => $currentUid,
                            'replyTime'   => time(),
                        ],
                    ]
                ))
            )->onQueue(Appraise::QUEUE_NAME);
            //飞书通知-评价反馈客服飞书群群+圈对应的人（客服某一个人）
             /*self::sendFSMessage(
                 $info['shopId'], $info['createdByUid'], $id, (string)$info['workOrderNo'], (int)$info['type'],
                 (int)$info['score'], $info['tagDesc'], (string)$info['desc'], [], $info['createdAt']->toDateTimeString(),
                 [
                     'status'      => AppraiseModel::STATUS_DEAL_ING,
                     'replyUserId' => $currentUid,
                     'replyTime'   => time(),
                 ]
             );*/
        }
    }

    /**
     * 处理评价-完成
     * @param $id
     * @param $currentUid
     */
    public static function update($id, $currentUid)
    {
        $info = AppraiseModel::query()->find($id);
        if (!$info) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的评价id");
        }
        /*if ($info['dealUid'] != $currentUid) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "非当前处理人");
        }
        if ($info['status'] != AppraiseModel::STATUS_DEAL_ING) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "当前状态非处理中");
        }*/
        $data = [
            'status'       => AppraiseModel::STATUS_DEAL_SUC,
            'dealTime'     => time(),
            'updatedByUid' => $currentUid,
        ];
        AppraiseModel::setInfoById($id, $data);

        // 操作日志
        OperateLogModel::add(
            OperateLogModel::BUSINESS_APPRAISE,
            $id,
            $id,
            "评价处理完成",
            "",
            OperateLogModel::STATUS_OK,
            $currentUid,
        );
    }


    /**
     * 获取评价对应内容配置-new
     * @param int $type
     * @return array
     */
    public static function getNewConfig($type = AppraiseModel::TYPE_ALL): array
    {
        $configs = Cache::remember(
            'tiger:workOrder:appraise:template', config('app.env') == 'prod' ? 600 : 1, function () {
            return ConfigModel::query()
                ->where('module', 'appraise')
                ->get()
                ->toArray();
        }
        );
        $datas   = [];
        if ($type != AppraiseModel::TYPE_ALL && !isset(AppraiseModel::TYPE_MAP_TEXT[$type])) {
            return $datas;
        }
        foreach ($configs as $configArr) {
            $data = json_decode($configArr['value'], true);
            if(empty($data["stars"])){
                $data["stars"] = new \stdClass();
            }
            if ($type != AppraiseModel::TYPE_ALL) {
                if ($configArr['name'] == ('template:' . AppraiseModel::TYPE_MAP_TEXT[$type])) {
                    return $data;
                }
            } else {
                if (strstr($configArr['name'],'template:')) {
                    $datas[] = array_merge($data, ['name' => str_replace( 'template:','', $configArr['name'])]);
                }
            }
        }
        return $datas;
    }


    /**
     * 订单状态验证
     * @param int $type
     * @param string $workOrderNo
     * @return array|bool
     * @throws GuzzleException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function orderStatusValidate(int $type, string $workOrderNo = '')
    {
        if (!in_array($type, AppraiseModel::NOT_ORDER_NO_MAPPING) || $workOrderNo) {
            $orderDetail = [];
            if (config('app.env') == 'qa' || config('app.env') == 'pre') {
                $appraiseExpireTime = strtotime(date("Y-m-d", strtotime("-3 Months")));//time() - 300;
            } else {
                $appraiseExpireTime = strtotime(date("Y-m-d", strtotime("-" . self::DEFAULT_APPRAISE_EXPIRE_DAY . " Months")));
            }
            switch ($type) {
                case AppraiseModel::TYPE_WORK_ORDER://工单
                    $orderDetail = WorkOrderApplyMainModel::getDetailByWorkOrderNo($workOrderNo);
                    if ($type == AppraiseModel::TYPE_WORK_ORDER && $orderDetail && $orderDetail->completeTime < $appraiseExpireTime) {//3个月内已完成的工单，可以评价
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "订单评价时间已过");
                    }
                    break;
                case AppraiseModel::TYPE_WAIMAI_OPENING://外卖-上线外卖
                case AppraiseModel::TYPE_GROUP_PURCHASE_OPENING://团购-上线团购
                    $orderDetail = [1];
                    break;
                case AppraiseModel::TYPE_OPENSHOP_SIGN://开店-签约阶段 关联 开店订单
                case AppraiseModel::TYPE_OPENSHOP_SET_LOCATION://开店-选址阶段 关联 开店订单
                case AppraiseModel::TYPE_OPENSHOP_PREPARATION://开店-筹备阶段 关联 开店订单
                case AppraiseModel::TYPE_OPENSHOP_OPENING://开店-开业阶段 关联 开店订单
                case AppraiseModel::TYPE_APP_SHOP_DESIGN://商家APP-门店设计
                    $orderDetail = OpenShopSignOrderModel::orderDetail($workOrderNo);
                    break;
                case AppraiseModel::TYPE_OPENSHOP_COLLEGE://商学院培训 关联 培训订单
                    $orderDetail = CollegeTrainingOrderModel::query()->where('orderNo', $workOrderNo)->select(['status'])->first();
                    if ($orderDetail && $orderDetail->status != CollegeTrainingOrderModel::STATUS_FINISH) {
                        throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "订单状态未完成");
                    }
                    break;
                case AppraiseModel::TYPE_KFOS_FIRST_ORDER:
                case AppraiseModel::TYPE_KFOS_ORDER://首批订货和日常订货 关联 订货单
                    $applyContent = OrmNewOrderRemote::detail(0, $workOrderNo);//获取订货详情
                    $code         = $applyContent['code'] ?? -1;
                    if ($code == 0) {
                        $orderDetail = $applyContent['data'] ?? [];
                        if ($orderDetail && $orderDetail['status'] != 3) {
                            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "订单状态未完成");
                        }
                    }
                    break;
            }
            if (!$orderDetail) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的订单");
            }
            $appraiseInfo = AppraiseModel::getInfoByWorkOrderNo($workOrderNo, $type);
            if ($appraiseInfo) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "订单已评价");
            }
        }
        return true;
    }

    /**
     * 通过业务订单ID和类型查询详情
     * @param $workOrderNos
     * @param $types
     * @return array
     */
    public static function getInfoByOrderNos($workOrderNos, $types): array
    {
        return AppraiseModel::getInfoByWorkOrderNos($workOrderNos, $types);
    }


    /**
     * 饿了么外卖上线&美团外卖上线-其中一个平台，上线外卖2周后，进行推送 评价消息
     * 点评团购上线&抖音团购上线-其中一个平台，上线外卖2周后，进行推送 评价消息
     * 首批订货，进行推送 评价消息
     * @param $workOrderNo
     * @param $shopId
     * @param $type
     * @return array
     */
    public static function checkEventNotify($workOrderNo, $shopId, $type): array
    {
        if (in_array($type, [AppraiseModel::TYPE_WAIMAI_OPENING, AppraiseModel::TYPE_GROUP_PURCHASE_OPENING, AppraiseModel::TYPE_KFOS_FIRST_ORDER])) {
            $task = AppraiseMessageTaskModel::query()
                ->where('shopId', $shopId)
                ->where('type', $type)
                ->first();
            if ($task) {//同一平台发送一次
                return [];
            }
        }
        NotifyService::notify($workOrderNo, $type, 0, $shopId);
        return [];
    }

    /**
     * 获取评价对应处理人配置
     * @return array
     */
    public static function getDealConfig(): array
    {
        return Cache::remember(
            'tiger:workOrder:appraise:appraiseRoleList', getSwitchCacheTime(86400), function () {
            return json_decode(
                ConfigModel::query()
                    ->where('module', 'appraise')
                    ->where('name', 'appraiseRoleList')
                    ->value('value') ?? '', true
            );
        }
        );
    }

    /**
     * 异步推送评价反馈消息
     * @param $data
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function sendFSMessageJobs($data)
    {
        if (!$data['img'] && !$data['replyData']) {//无图片且非回复时 直接发送
            self::sendFSMessage(
                $data['shopId'],
                $data['currentUid'],
                $data['appraiseId'],
                $data['workOrderNo'],
                $data['type'],
                $data['score'],
                $data['tagDesc'],
                $data['desc'],
                [],
                $data['createTime'],
                []
            );
            return;
        }
        $resourcesList = [];
        $info          = AppraiseModel::query()->with(['resourcesRel'])->find($data['appraiseId']);
        if (!$info) {
            return;
        }
        //图片上传至飞书 用于卡片通知
        $saveDir    = getTmpDir("/workOrder/appraise/" . formatDateYmd(time()));
        $fileSystem = getFileSystem();
        if (!$fileSystem->isDirectory($saveDir)) {
            $fileSystem->makeDirectory($saveDir, 0777, true);
        }
        //资源数据
        collect($info->resourcesRel)->each(
            function (ResourcesModel $resourcesModel) use ($data, $fileSystem, $saveDir, &$resourcesList) {
                $file     = picturePath($resourcesModel->url) . '?x-oss-process=image/resize,m_fill,h_800,w_800';
                $fsImgKey = $resourcesModel->extra ? (json_decode($resourcesModel->extra, true)['fsImgKey'] ?? "") : "";
                if (!$fsImgKey) {
                    $filePath = vsprintf(
                        "%s/%s.%s", [
                            $saveDir,
                            md5($file),
                            (new \SplFileInfo($file))->getExtension()
                        ]
                    );
                    $fileSystem->put(
                        $filePath,
                        file_get_contents($file)
                    );
                    try {
                        $fsImgKey              = FeishuImageRemote::uploadImage($filePath)['image_key'];//图片上传至飞书
                        $resourcesModel->extra = json_encode(['fsImgKey' => $fsImgKey]);
                        $resourcesModel->save();
                    } catch (Exception $exception) {
                        logInfo(
                            '评价反馈图片上传至飞书报错', collect(
                            [
                                'file'       => $file,
                                'appraiseId' => $data['appraiseId'],
                                'msg'        => $exception->getMessage(),
                            ]
                        ), true, true
                        );
                    }
                }
                if ($fsImgKey) {
                    $resourcesList[] = [
                        'file'     => $file,
                        'fsImgKey' => $fsImgKey,
                    ];
                }
            }
        )->toArray();

        //飞书通知-评价反馈客服飞书群群+圈对应的人（客服某一个人）
        self::sendFSMessage(
            $data['shopId'],
            $data['currentUid'],
            $data['appraiseId'],
            $data['workOrderNo'],
            $data['type'],
            $data['score'],
            $data['tagDesc'],
            $data['desc'],
            $resourcesList,
            $data['createTime'],
            $data['replyData']
        );
    }

    /**
     * 通过门店编号查询对应开店订单数据
     * @param $shopCode
     * @return array
     */
    public static function getOpenShopSignOrderData($shopCode): array
    {
        $addressPrefix = $addressDetail = $province = $branch = $managerId = '';
        $openShopSignOrderModel = OpenShopSignOrderModel::query()
            ->with(['addressRel'])
            ->where('shopCode', $shopCode)
            ->orderByDesc('id')
            ->first();
        if ($openShopSignOrderModel) {
            $managerId = OpenShopOrderManagerModel::getManagerUid($openShopSignOrderModel->mainProcessId ?? 0, OpenShopOrderManagerModel::MANAGER_TYPE_5);//督导
            if ($openShopSignOrderModel->addressRel) {
                $addressPrefix = $openShopSignOrderModel->addressRel->addressPrefix ?? "";
                $addressDetail = $openShopSignOrderModel->addressRel->addressDetail ?? "";
                $province      = $openShopSignOrderModel->addressRel->provinceCode ?? "";

                // 查询省份对应分公司
                $getBranch = (new OpenShopOrganizationManageModel)->getBranchByProvinceCode([$province]);
                if ($getBranch) {
                    $getBranch = $getBranch->keyBy('provinceCode')->toArray();
                    if ($getBranch && isset($getBranch[$province])) {
                        $branch = $getBranch[$province]['name'];
                    }
                }
            }
        }
        return [
            'addressDetail' => $addressDetail,// 详细地址
            'addressPrefix' => $addressPrefix,// 省市区
            'province'      => $province,     // 省code
            'branch'        => $branch,       // 分公司
            'managerId'     => $managerId,    // 督导id
        ];
    }
}
